module top_module (
    input clk,
    input reset,   // Synchronous reset
    input s,
    input w,
    output z
);

    parameter A = 1'b0;
    parameter B = 1'b1;
    
    reg		state;
    reg		next_state;
    
    always @(posedge clk) begin
        if(reset) begin
            state <= A;
        end
        else begin
            state <= next_state;
        end
    end
    
    reg		w1;
    reg		w2;
    
    always @(posedge clk) begin
        if(reset) begin
            w1 <= 1'b0;
            w2 <= 1'b0;
        end
        else if(next_state == B) begin
            w2 <= w1;
            w1 <= w;
        end
        else begin
            w2 <= 1'b0;
            w1 <= 1'b0;
        end
    end
    
    always @(*) begin
        case(state)
            A:		next_state = s ? B : A;
            B:		next_state = B;
        endcase
    end
    
    reg	[1:0]	cnt;
    
    always @(posedge clk) begin
        if(reset) begin
            cnt <= 2'd0;
        end
        else if(cnt == 2'd2)begin
            cnt <= 2'd0;
        end
        else if(next_state == B) begin
            cnt <= cnt + 1'b1;
        end
    end
    
    always @(posedge clk) begin
        if(reset) begin
            z <= 1'b0;
        end
        else if((state == B) && (cnt == 2'd0)) begin
            if(w&w1&~w2 | w&~w1&w2 | ~w&w1&w2) begin
                z <= 1'b1;
            end
            else begin
                z <= 1'b0;
            end
        end
        else begin
            z <= 1'b0;
        end
    end
    
endmodule
